const app = getApp();
const _requsetCYZ = require('../../utils/requestData');
const _functionCYZ = require('../../utils/common');
var WxParse = require('../../wxParse/wxParse.js');
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');// 引入SDK核心类
Page({
    data: {
        this_app_muchcity_open: false,
        this_app_muchcity_select: 2,
        this_cate_list: null,
        this_old_cate_list: null,
        this_config_data: null,
        this_shop_data: null,
        this_ad_list: null,
        this_huodong_list: null,
        this_ruzhu_new_data: null,
        this_ruzhu_rmp_data: null,
        this_shop_list: null,
        this_cate_id: 0,
        this_cate_name: '全部',
        this_s_keywords: '',
        select_type: 0,
        this_u_lat: 0,
        this_u_lng: 0,
        this_user_city: '全国',
        this_page_size: 1,
        this_page_num: 10,
        is_loadmore: true,
        this_user_select_city: '',
        select_city_layer_status: false,
        this_show_juli: false,
        is_alert_content_t: false,
        is_close_in: false,
        is_show_catelist: false
    },
    //选择分类显示
    select_cate_bind: function () {
        this.setData({ is_show_catelist: this.data.is_show_catelist ? false : true });
    },
    set_alert_content_close_t: function () {
        this.setData({ is_alert_content_t: false, is_close_in: true });
    },
    change_cate_bind: function (e) {
        this.setData({ this_cate_id: e.currentTarget.dataset.id, this_page_size: 1, this_cate_name: e.currentTarget.dataset.name });
        this.setData({ is_show_catelist: false, is_loadmore: true });
        this.getIndexData();
    },
    select_city_bind: function (e) {
        var that = this;
        var this_c_name = e.currentTarget.dataset.name;
        var this_c_field = e.currentTarget.dataset.field;
        that.setData({ this_city_field: this_c_field, this_user_select_city: this_c_name });
        that.setData({ this_city_parent_level: e.currentTarget.id });
        _functionCYZ.CYZ_loading();
        var requestData = {};
        requestData.parent_level = that.data.this_city_parent_level;
        _requsetCYZ.cyz_requestGet('/Index/getCityList', requestData, function (xyz_data) {
            wx.hideToast();
            if (xyz_data.info == null) {
                that.set_alert_content_confrim();
                return false;
            }
            that.setData({ this_city_data: xyz_data.info, select_city_layer_status: true });
        });
    },
    set_alert_content_setno: function () {
        var that = this;
        this.set_alert_content_close();
    },
    //关闭城市
    set_alert_content_close: function () {
        this.setData({ this_city_data: [], select_city_layer_status: false, this_city_parent_level: 1, this_city_field: 1 });
    },
    //确认选择
    set_alert_content_confrim: function () {
        var that = this;
        that.setData({ this_city_data: [], select_city_layer_status: false, this_city_parent_level: 1, this_city_field: 1, this_page_size: 1, is_loadmore: true, this_s_keywords: that.data.this_s_keywords, this_user_city: that.data.this_user_select_city });
        that.getIndexData();
    },
    //自动定位
    user_location_bind: function () {
        this.getLocation();
    },
    //搜索
    info_search_bind: function (e) {
        this.setData({ this_page_size: 1, is_loadmore: true, this_s_keywords: e.detail.value });
        this.getIndexData();
    },
    getLocation: function () {
        var that = this;
        let qqmapsdk = null;
        _requsetCYZ.cyz_requestGet('/ShopApi/getDailiQQmapKey', {}, function (res) {
            qqmapsdk = new QQMapWX({ key: res.info.mapkey});
            _functionCYZ.CYZ_loading("定位中，请稍候...");
            wx.getLocation({
                type: 'gcj02',
                success: function (res) {
                    qqmapsdk.reverseGeocoder({
                        location: {
                            latitude: res.latitude,
                            longitude: res.longitude
                        },
                        success: (res) => {
                            that.setData({ sdk_user_address_info: res.result });
                            wx.setStorageSync('global_user_city', res.result.address_component.city);
                            wx.setStorageSync('global_user_address', res.result.address);
                            wx.setStorageSync('global_user_lat', res.result.location.lat);
                            wx.setStorageSync('global_user_lng', res.result.location.lng);
                            wx.setStorageSync('global_user_province', res.result.address_component.province);
                            wx.setStorageSync('global_user_city', res.result.address_component.city);
                            wx.setStorageSync('global_user_district', res.result.address_component.district);
                            that.getSystemData();
                            that.set_alert_content_close();
                        }
                    });
                },
                fail: function () {
                    //弹出系统设置
                    wx.openSetting({
                        success: (res) => {
                            if (res.authSetting['scope.userLocation'] == false) {
                                wx.showModal({
                                    title: '提示',
                                    content: "请允许地理位置授权",
                                    showCancel: false,
                                    success: function () {
                                        that.getLocation();
                                    }
                                });
                            } else {
                                that.getLocation();
                            }
                        }
                    });
                    return false;
                },
                complete: function () {
                    wx.hideLoading();
                }
            })
        })
    },
    onSwtchTabTap: function (e) {
        var that = this;
        const dataset = e.currentTarget.dataset, index = dataset.index;
        this.setData({this_page_size: 1, is_loadmore: true, select_type: index });
        if (index == 1) {
            if (wx.getStorageSync("global_user_address")) {
                that.getIndexData();
            } else {
                that.getLocation();
            }
        } else {
            this.getIndexData();
        }
    },
    onLoad: function (op) {
        var that = this;
        that.setData({ this_cate_id: op.cate_id, this_cate_name: op.cate_name||'全部', this_s_keywords: '', this_page_size: 1 });
        that.getLocation();
        // if (wx.getStorageSync('global_user_address')) {
        //     that.getSystemData();
        // } else {
        //     that.getLocation();
        // }
    },
    getSystemData: function () {
        var that = this;
        //加载系统配置
        _requsetCYZ.cyz_requestGet('/Index/getConfigOthersValue', {}, function (xyz_data) {
            that.setData({ this_app_muchcity_open: xyz_data.info.app_muchcity_open });
            //如果缓存存在
            var user_city_fanwei = "全国";
            if (wx.getStorageSync('global_user_address')) {
                if (xyz_data.info.app_muchcity_select == 1) {
                    user_city_fanwei = wx.getStorageSync("global_user_province");
                } else if (xyz_data.info.app_muchcity_select == 2) {
                    user_city_fanwei = wx.getStorageSync("global_user_city");
                } else if (xyz_data.info.app_muchcity_select == 3) {
                    user_city_fanwei = wx.getStorageSync("global_user_district");
                }
                that.setData({
                    this_user_city: user_city_fanwei,
                    this_u_lat: wx.getStorageSync("global_user_lat"),
                    this_u_lng: wx.getStorageSync("global_user_lng")
                });
            } else {
                if (xyz_data.info.app_muchcity_select == 1) {
                    user_city_fanwei = that.data.sdk_user_address_info.address_component.province;
                } else if (xyz_data.info.app_muchcity_select == 2) {
                    user_city_fanwei = that.data.sdk_user_address_info.address_component.city;
                } else if (xyz_data.info.app_muchcity_select == 3) {
                    user_city_fanwei = that.data.sdk_user_address_info.address_component.district;
                }
                that.setData({
                    this_user_city: user_city_fanwei,
                    this_u_lat: that.data.sdk_user_address_info.location.lat,
                    this_u_lng: that.data.sdk_user_address_info.location.lng
                });
            }

            if (xyz_data.info.app_muchcity_open == false) {
                that.setData({
                    this_user_city: '全国'
                });
            }
            that.getIndexData();
        });
        //that.getIndexData();
    },
    getIndexData: function () {
        var that = this;
        _functionCYZ.CYZ_loading();
        var requestData = {};
        requestData.pagesize = that.data.this_page_size;
        requestData.pagenum = that.data.this_page_num;
        requestData.keywords = that.data.this_s_keywords;
        requestData.cate_id = that.data.this_cate_id;
        requestData.u_city = that.data.this_user_city;
        requestData.select_type = that.data.select_type;
        requestData.u_lat = that.data.this_u_lat;
        requestData.u_lng = that.data.this_u_lng;
        _requsetCYZ.cyz_requestGet('/BusinessApi/index', requestData, function (cyz_data) {
            wx.hideToast();

            var tuijian_data_rmp = [];
            if (cyz_data.info.shop_tuijian_ruzhu != null) {
                var i = -1;
                for (var j = 0; j < cyz_data.info.shop_tuijian_ruzhu.length; j++) {
                    if (j % 3 === 0) {
                        tuijian_data_rmp[++i] = [];
                    }
                    const item = cyz_data.info.shop_tuijian_ruzhu[j];
                    tuijian_data_rmp[i].push(item);
                }
            } else {
                tuijian_data_rmp = null;
            }


            that.setData({
                this_ad_list: cyz_data.info.index_ad_lunbo,
                this_config_data: cyz_data.info.index_config,
                this_ruzhu_new_data: cyz_data.info.shop_new_ruzhu,
                this_shop_list: cyz_data.info.shop_list,
                this_shop_data: cyz_data.info.shop_index_data,
                this_ruzhu_rmp_data: tuijian_data_rmp,
                this_huodong_list: cyz_data.info.index_huodong_list,
                this_old_cate_list: cyz_data.info.business_cate_list
            });

            if (that.data.is_close_in == false) {
                if (cyz_data.info.index_config.shuoming_is_open == 1) {
                    that.setData({ is_alert_content_t: true });
                }
            }
            WxParse.wxParse('article', 'html', cyz_data.info.index_config.shangjia_index_shuoming, that, 5);
            const group = [], styles = {};
            var i = -1;
            for (var x in cyz_data.info.business_cate_list) {
                if (x % 8 === 0) {
                    group[++i] = [];
                }
                const item = cyz_data.info.business_cate_list[x];
                group[i].push(item);
                try {
                    styles[item.id] = JSON.parse(item.style ? item.style : "{}");
                } catch (e) {
                    console.error(e);
                }
            }
            if (cyz_data.info.shop_list == null) {
                that.setData({ is_loadmore: false });
            } else {
                if (cyz_data.info.shop_list.length < that.data.this_page_num) {
                    that.setData({ is_loadmore: false });
                }
            }
            that.setData({ this_cate_list: group });
            wx.setNavigationBarTitle({
                title: cyz_data.info.index_config.shop_title + '-' + that.data.this_cate_name
            });
        });
    },
    onReachBottom: function (e) {
        var that = this;
        if (that.data.is_loadmore == false) {
            return false;
        }
        _functionCYZ.CYZ_loading();
        var requestData = {};
        requestData.pagesize = that.data.this_page_size + 1;
        requestData.pagenum = that.data.this_page_num;
        requestData.cate_id = that.data.this_cate_id;
        requestData.keywords = that.data.this_s_keywords;
        requestData.u_city = that.data.this_user_city;
        requestData.select_type = that.data.select_type;
        requestData.u_lat = that.data.this_u_lat;
        requestData.u_lng = that.data.this_u_lng;
        _requsetCYZ.cyz_requestGet('/BusinessApi/index', requestData, function (xyz_data) {
            wx.hideToast();

            if (xyz_data.info.shop_list == null) {
                that.setData({ is_loadmore: false });
            } else {
                if (xyz_data.info.shop_list.length < that.data.this_page_num) {
                    that.setData({ is_loadmore: false });
                }
                var this_new_info_data = that.data.this_shop_list;
                this_new_info_data = this_new_info_data.concat(xyz_data.info.shop_list);
                that.setData({ this_shop_list: this_new_info_data, this_page_size: requestData.pagesize });
            }

        });
    },
    /**
     * 拨打电话
     */
    onCallTap: function (e) {
        const mobile = e.currentTarget.dataset.mobile;
        wx.makePhoneCall({
            phoneNumber: mobile,
        });
    },
    //广告链接跳转
    go_ad_url_bind: function (e) {
        wx.navigateTo({ url: e.currentTarget.dataset.url });
    },
    //链接跳转
    go_url_bind: function (e) {
        wx.navigateTo({ url: e.currentTarget.dataset.url });
    },
    //跳转商家
    go_shop_info_action:function(e){
        let _this = this;
        let this_index = e.currentTarget.dataset.index;
        let this_shop_data = _this.data.this_shop_list[this_index];
        if(this_shop_data.is_have_wxapp == 1){
            wx.navigateToMiniProgram({
                appId: this_shop_data.have_wxapp_appid
            })
        }else{
            wx.navigateTo({
                url: '/pages/business_detail/index?id=' + this_shop_data.id,
            })
        }
    },
    //地图跳转
    go_map_info_b: function () {
        var that = this;
        var t_address = that.data.this_cms_config.cms_address;
        _requsetCYZ.cyz_requestGet('/Map/getLocation', { address: t_address }, function (xyz_data) {
            wx.openLocation({
                latitude: parseFloat(xyz_data.info.lat),
                longitude: parseFloat(xyz_data.info.lng),
                scale: 18,
                address: t_address
            });
        });
    },
    onPullDownRefresh: function () {
        var that = this;
        that.setData({ this_page_size: 1, is_loadmore: true });
        that.getIndexData();
        setTimeout(() => {
            wx.stopPullDownRefresh()
        }, 1000);
    }
})